<template>
  <view class="webview-container">
    <view class="header" v-if="!fullScreen">
      <view class="back-btn" @tap="handleBack">
        <text class="back-icon">&lt;</text>
      </view>
      <view class="title">{{ title }}</view>
      <view class="right-space"></view>
    </view>
    <!-- 加载指示器 -->
    <view class="loading-indicator" v-if="isLoading">
      <uni-loading type="circle" text="加载中..."></uni-loading>
    </view>
    <!-- 错误提示 -->
    <view class="error-container" v-if="showError">
      <image src="/static/other/error.png" class="error-icon" mode="aspectFit"></image>
      <text class="error-text">{{ errorMessage }}</text>
      <button class="retry-button" @tap="retryLoad">重试</button>
      <button class="copy-button" @tap="copyUrl">复制链接</button>
    </view>
    <!-- 主要web-view内容 -->
    <web-view 
      v-if="!showError"
      :src="url" 
      @message="handleMessage" 
      @load="onWebviewLoad"
      @error="onWebviewError"
    ></web-view>
  </view>
</template>

<script>
export default {
  name: 'webview',
  data() {
    return {
      url: '',
      title: '网页',
      fullScreen: false,
      isLoading: true,
      showError: false,
      errorMessage: '页面加载失败，请检查网络连接后重试'
    }
  },
  onLoad(options) {
    // 从参数中获取URL和标题
    if (options.url) {
      try {
        this.url = decodeURIComponent(options.url);
        console.log('加载的URL:', this.url);
        
        // 验证URL格式
        if (!this.url) {
          this.showError = true;
          this.errorMessage = '无效的URL地址';
          this.isLoading = false;
        } else if (this.url.startsWith('qqmap://')) {
          // 特殊处理：腾讯地图的自定义协议
          console.warn('检测到QQMap自定义协议，将尝试转换为标准URL');
          // 直接显示错误提示，引导用户使用复制链接功能
          this.showError = true;
          this.errorMessage = '无法在WebView中打开地图应用，请复制链接在浏览器中打开';
          this.isLoading = false;
        } else if (!this.url.startsWith('https://')) {
          // 其他非HTTPS URL也显示错误
          this.showError = true;
          this.errorMessage = '无效的URL地址';
          this.isLoading = false;
        } else if (this.url.includes('apis.map.qq.com')) {
          // 特别处理腾讯地图路线规划URL，添加防重定向参数
          // console.log('检测到腾讯地图路线规划URL，增强处理');
          // 添加参数防止重定向到自定义协议
          if (!this.url.includes('redirect=no')) {
            this.url += (this.url.includes('?') ? '&' : '?') + 'redirect=no';
            // console.log('增强后的URL:', this.url);
          }
        }
      } catch (e) {
        // console.error('解码URL失败:', e);
        this.showError = true;
        this.errorMessage = 'URL格式错误，请检查链接';
        this.isLoading = false;
      }
    } else {
      this.showError = true;
      this.errorMessage = '未指定要加载的URL';
      this.isLoading = false;
    }
    
    if (options.title) {
      this.title = decodeURIComponent(options.title);
    }
    
    if (options.fullScreen) {
      this.fullScreen = options.fullScreen === 'true';
    }
    
    // 设置页面标题
    uni.setNavigationBarTitle({
      title: this.title
    });
  },
  methods: {
    // 返回上一页
    handleBack() {
      uni.navigateBack();
    },
    
    // 处理web-view发送的消息
    handleMessage(e) {
      // console.log('web-view message:', e);
      // 可以在这里处理从web-view页面发送的消息
    },
    
    // web-view加载完成回调
    onWebviewLoad() {
      // console.log('web-view加载完成');
      this.isLoading = false;
    },
    
    // web-view加载错误回调
    onWebviewError(e) {
      // console.error('web-view加载错误:', e);
      this.isLoading = false;
      this.showError = true;
      
      // 根据错误类型提供更具体的错误信息
      if (e.errMsg && e.errMsg.includes('ERR_UNKNOWN_URL_SCHEME')) {
        this.errorMessage = '无法直接打开地图应用，请在外部浏览器中打开或使用地图APP';
      } else if (e.errMsg && e.errMsg.includes('net::ERR_NAME_NOT_RESOLVED')) {
        this.errorMessage = '网络连接失败，请检查网络设置';
      } else if (e.errMsg && e.errMsg.includes('net::ERR_CONNECTION_TIMED_OUT')) {
        this.errorMessage = '连接超时，请稍后重试';
      } else {
        this.errorMessage = '页面加载失败，请检查网络连接后重试';
      }
    },
    
    // 重试加载
    retryLoad() {
      this.isLoading = true;
      this.showError = false;
      // 重置web-view，强制重新加载
      const tempUrl = this.url;
      this.url = '';
      this.$nextTick(() => {
        this.url = tempUrl;
      });
    },
    
    // 添加复制URL功能，帮助用户在外部浏览器打开
    copyUrl() {
      uni.setClipboardData({
        data: this.url,
        success: () => {
          uni.showToast({
            title: '链接已复制，请在浏览器中打开',
            icon: 'none',
            duration: 2000
          });
        },
        fail: () => {
          uni.showToast({
            title: '复制失败，请手动复制链接',
            icon: 'none',
            duration: 2000
          });
        }
      });
    }
  }
}
</script>

<style scoped>
.webview-container {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
}

.header {
  height: 44px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
  background-color: #ffffff;
  border-bottom: 1px solid #eeeeee;
}

.back-btn {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  font-size: 18px;
  color: #333333;
}

.title {
  flex: 1;
  text-align: center;
  font-size: 16px;
  font-weight: 500;
  color: #333333;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  padding: 0 10px;
}

.right-space {
  width: 40px;
}

/* 加载指示器样式 */
.loading-indicator {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
}

/* 错误提示样式 */
.error-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
  padding: 40rpx;
}

.error-icon {
  width: 160rpx;
  height: 160rpx;
  margin-bottom: 30rpx;
}

.error-text {
  font-size: 28rpx;
  color: #666;
  text-align: center;
  margin-bottom: 40rpx;
  line-height: 1.5;
}

.retry-button {
    width: 240rpx;
    height: 80rpx;
    line-height: 80rpx;
    font-size: 28rpx;
    color: #fff;
    background-color: #007aff;
    border-radius: 40rpx;
    border: none;
  }
  
  .retry-button:active {
    background-color: #0051d5;
  }
  
  .copy-button {
    margin-top: 15rpx;
    padding: 12rpx 40rpx;
    background-color: #f8f8f8;
    color: #333;
    border: 1rpx solid #ddd;
    border-radius: 8rpx;
    font-size: 28rpx;
  }
  
  .copy-button:active {
    background-color: #e8e8e8;
  }

/* 设置web-view的样式 */
/deep/ web-view {
  flex: 1;
  width: 100%;
  height: 100%;
}
</style>